package com.onccc.social

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.accessibility.AccessibilityEvent
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.StringUtils
import com.google.gson.Gson
import com.onccc.social.databinding.ActivityMainBinding
import com.onccc.social.evet.OnCommentListener
import com.onccc.social.evet.OnCopyWriteListener
import com.onccc.social.evet.OnInterestListener
import com.onccc.social.net.BitmapToBase64Util
import com.onccc.social.model.CommentModel
import com.onccc.social.model.CommentPostModel
import com.onccc.social.model.CopyWriteModel
import com.onccc.social.model.CopyWritePostModel
import com.onccc.social.model.ImageInterestModel
import com.onccc.social.model.ImagePostModel
import com.onccc.social.model.KeywordListModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.io.IOException


class MainActivity : AppCompatActivity(), AssistsServiceListener {
    private val viewBind: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater).apply {
            btnOption.setOnClickListener {
                if (Assists.isAccessibilityServiceEnabled()) {
                    OverManager.show()
                } else {
                    Assists.openAccessibilitySetting()
//                    startActivity(Intent(this@MainActivity, SettingGuideActivity::class.java))
                }
            }

            ll.setOnTouchListener { v, event ->
                // 获取触摸事件的类型
                val action = event.action
                when (action) {
                    MotionEvent.ACTION_DOWN -> {}
                    MotionEvent.ACTION_MOVE -> {}
                    MotionEvent.ACTION_UP -> {
                        // 当抬起时的处理
                        // 获取点击位置的X、Y坐标
                        val x = event.x
                        val y = event.y
                        Log.d("ClickPosition", "x: $x, y: $y")
                    }
                }
                true // 返回true表示已消费事件，不再传递
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkServiceEnable()
    }

    private fun checkServiceEnable() {
        if (Assists.isAccessibilityServiceEnabled()) {
            viewBind.btnOption.text = "显示操作浮窗"
        } else {
            viewBind.btnOption.text = "开启服务"
        }
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        super.onAccessibilityEvent(event)
        if (event.eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {

        }
    }

    override fun onServiceConnected(service: AssistsService) {
        onBackApp()
    }

    private fun onBackApp() {
        Assists.coroutine.launch {
            while (Assists.getPackageName() != packageName) {
                Assists.back()
                delay(500)
            }
        }
    }

    override fun onUnbind() {
        OverManager.clear()
        checkServiceEnable()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils.setStatusBarLightMode(this, true)
        setContentView(viewBind.root)
        Assists.serviceListeners.add(this)
        if (!Assists.isEnableScreenCapture()) {
            Assists.requestScreenCapture(true)
        }
        getKeywordsList()
    }

    override fun onDestroy() {
        super.onDestroy()
        Assists.serviceListeners.remove(this)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        super.onBackPressed()
        moveTaskToBack(true)
    }

    companion object {

        public fun getInputTime(): Long {
            return java.util.Random().nextInt(1500).toLong()
        }

        public fun getOneTime(): Long {
            return 500 + (java.util.Random().nextInt(2000)).toLong()
        }

        public fun getTwoTime(): Long {
            return (1500 + java.util.Random().nextInt(2000)).toLong()
        }

        public fun getThreeTime(): Long {
            return (2500 + java.util.Random().nextInt(2000)).toLong()
        }

        public fun getFiveTime(): Long {
            return (4500 + java.util.Random().nextInt(2000)).toLong()
        }

        var keywordsList = ArrayList<String>()

        fun getKeyword(): String {
            var keyword = StringUtils.getString(R.string.keyword_cn)
            if (keywordsList.size != 0) {
                keyword = keywordsList[java.util.Random().nextInt(keywordsList.size)]
            }
            return keyword
        }

        fun getKeywordsList() {
            getKeywordsList("english")
        }

        fun getKeywordsList(lang: String) {
            val postBean = CommentPostModel()
            postBean.setProfile(StringUtils.getString(R.string.tag))
            postBean.setLang(lang)
            val postJson = Gson().toJson(postBean)
            OverManager.log("生成兴趣关键词")

            val mediaType = "application/json".toMediaTypeOrNull()
            val requestBody: RequestBody = RequestBody.create(mediaType, postJson)
            val client = OkHttpClient()
            val request: Request = Request.Builder()
                    .url("https://iris.iigood.com/iris/v1/agent/keywords")
                    .post(requestBody)
                    .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {

                }

                @Throws(IOException::class)
                override fun onResponse(call: Call, response: okhttp3.Response) {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")

                    // 请求成功，获取数据
                    val responseData = response.body!!.string()
                    val keywordListModel: KeywordListModel = Gson().fromJson(responseData, KeywordListModel::class.java)
                    keywordsList = keywordListModel.keywords as ArrayList<String>
                }
            })
        }

        public fun getInterest(onSuccess: OnInterestListener, onError: Runnable) {

            val screenBitmap = Assists.screenCaptureService?.toBitmap()
            OverManager.log("获取截图")
            val imageList = ArrayList<String>()
            if (Assists.screenCaptureService != null && screenBitmap != null) {
                imageList.add("data:image/jpeg;base64," + BitmapToBase64Util.bitmapToBase64(screenBitmap))

                val postBean = ImagePostModel()
                postBean.setAttachments(imageList)
                postBean.setProfile(StringUtils.getString(R.string.tag))
                val postJson = Gson().toJson(postBean)
                OverManager.log("请求数据")

                val mediaType = "application/json".toMediaTypeOrNull()
                val requestBody: RequestBody = RequestBody.create(mediaType, postJson)
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                        .url("https://iris.iigood.com/iris/v1/agent/interest")
                        .post(requestBody)
                        .build()
                client.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        onError.run()
                    }

                    @Throws(IOException::class)
                    override fun onResponse(call: Call, response: okhttp3.Response) {
                        if (!response.isSuccessful) throw IOException("Unexpected code $response")

                        // 请求成功，获取数据
                        val responseData = response.body!!.string()
                        val interestModel: ImageInterestModel = Gson().fromJson(responseData, ImageInterestModel::class.java)
                        if (interestModel.isInterested || interestModel.isToComment || interestModel.isToFollow) {
                            onSuccess.onInterest(interestModel)
                        } else {
                            onError.run()
                        }
                    }
                })

            }
        }

        fun getPostContent(platform: String, onSuccess: OnCopyWriteListener, onError: Runnable) {
            OverManager.log("生成文案")

            val postBean = CopyWritePostModel()
            postBean.setPlatform(platform)
            postBean.setContent(StringUtils.getString(R.string.tag))
            val postJson = Gson().toJson(postBean)

            val mediaType = "application/json".toMediaTypeOrNull()
            val requestBody: RequestBody = RequestBody.create(mediaType, postJson)
            val client = OkHttpClient()
            val request: Request = Request.Builder()
                    .url("https://iris.iigood.com/iris/v1/agent/copywriting")
                    .post(requestBody)
                    .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    onError.run()
                }

                @Throws(IOException::class)
                override fun onResponse(call: Call, response: okhttp3.Response) {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")

                    // 请求成功，获取数据
                    val responseData = response.body!!.string()
                    val model: CopyWriteModel = Gson().fromJson(responseData, CopyWriteModel::class.java)
                    if (model.copywriting.isNullOrEmpty()) {
                        onError.run()
                    } else {
                        onSuccess.onCopyWrite(model)
                    }
                }
            })
        }

        fun getComment(onSuccess: OnCommentListener, onError: Runnable) {
            OverManager.log("获取评论")
            val stringBuffer = StringBuilder()
            Assists.getAllNodes().forEach {
                if (it.text != null && !TextUtils.isEmpty(it.text.toString()) && !it.text.isNullOrEmpty()) {
                    stringBuffer.append(it.text.toString())
                }
            }

            val postBean = CommentPostModel()
            postBean.setComments(stringBuffer.toString())
            postBean.setProfile(StringUtils.getString(R.string.tag))
            val postJson = Gson().toJson(postBean)
            OverManager.log("生成评论")

            val mediaType = "application/json".toMediaTypeOrNull()
            val requestBody: RequestBody = RequestBody.create(mediaType, postJson)
            val client = OkHttpClient()
            val request: Request = Request.Builder()
                    .url("https://iris.iigood.com/iris/v1/agent/comment")
                    .post(requestBody)
                    .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    onError.run()
                }

                @Throws(IOException::class)
                override fun onResponse(call: Call, response: okhttp3.Response) {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")

                    // 请求成功，获取数据
                    val responseData = response.body!!.string()
                    val commentModel: CommentModel = Gson().fromJson(responseData, CommentModel::class.java)
                    if (commentModel.comment.isNullOrEmpty()) {
                        onError.run()
                    } else {
                        onSuccess.onComment(commentModel)
                    }
                }
            })
        }

    }

}